package com.huanxing.cloud.user.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huanxing.cloud.common.core.desensitization.MobilePhoneDesensitization;
import com.huanxing.cloud.common.security.handler.HxBusinessException;
import com.huanxing.cloud.user.api.constants.MallUserConstants;
import com.huanxing.cloud.user.api.entity.UserInfo;
import com.huanxing.cloud.user.api.vo.UserRespVO;
import com.huanxing.cloud.user.mapper.UserInfoMapper;
import com.huanxing.cloud.user.service.IUserInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Objects;

/**
 * 商城用户
 *
 * @author lijx
 * @since 2022/2/26 16:37
 */
@Service
@RequiredArgsConstructor
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements IUserInfoService {

	private final MobilePhoneDesensitization mobilePhoneDesensitization = new MobilePhoneDesensitization();

	@Override
	public IPage<UserRespVO> getPage(Page page, UserInfo userInfo) {
		return baseMapper.selectAdminPage(page, userInfo);
	}

	@Override
	public boolean checkPhone(String phone) {
		if (StrUtil.isBlank(phone)) {
			throw new HxBusinessException("手机号为空");
		}
		return baseMapper.selectCount(Wrappers.<UserInfo>lambdaQuery().eq(UserInfo::getPhone, phone)) > 0;
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean updateAccountBalance(String userId, BigDecimal amount) {
		return baseMapper.update(new UserInfo(),
				Wrappers.<UserInfo>lambdaUpdate()
					.eq(UserInfo::getId, userId)
					.setSql(" account_balance = account_balance + " + amount)) > 0;
	}

	@Override
	public UserRespVO getUserById(String id) {
		UserInfo userInfo = this.getById(id);
		if (Objects.isNull(userInfo)) {
			return null;
		}

		UserRespVO userRespVO = new UserRespVO();
		BeanUtils.copyProperties(userInfo, userRespVO);
		return userRespVO;
	}

	@Override
	public UserInfo createUser(String phone, String clientType) {
		UserInfo userInfo = new UserInfo();
		userInfo.setUserGrade(MallUserConstants.USER_GRADE_0);
		userInfo.setAccountBalance(BigDecimal.ZERO);
		userInfo.setPhone(phone);
		userInfo.setUserSource(clientType);
		userInfo.setNickName(mobilePhoneDesensitization.serialize(userInfo.getPhone()));
		userInfo.setCreateBy(phone);
		this.save(userInfo);
		return userInfo;
	}

	@Override
	public boolean updatePoint(String userId, int point) {
		return baseMapper.update(new UserInfo(),
				Wrappers.<UserInfo>lambdaUpdate().eq(UserInfo::getId, userId).setSql(" point = point + " + point)) > 0;
	}

}
